<template>
  <div class="comments-container">
    <el-card class="header-card">
      <h2><el-icon><ChatLineSquare /></el-icon> 我的评论</h2>
    </el-card>

    <el-card v-loading="loading">
      <el-empty v-if="comments.length === 0 && !loading" description="暂无评论" />

      <transition-group name="comment-fade" tag="div" class="comments-list">
        <div class="comment-item" v-for="comment in comments" :key="comment.commentId">
          <div class="comment-header">
            <div class="dish-info">
              <el-avatar :size="50" icon="User" />
              <div class="dish-details">
                <h3>{{ comment.dish?.dishName }}</h3>
                <el-tag size="small">{{ comment.dish?.dishType }}</el-tag>
              </div>
            </div>
            <div class="comment-meta">
              <el-rate v-model="comment.rating" disabled />
              <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
            </div>
          </div>
          
          <div class="comment-content">
            <p>{{ comment.commentContent }}</p>
            <div class="comment-images" v-if="comment.commentImages && comment.commentImages.trim()">
              <div class="comment-image-gallery">
                <img
                  v-for="(imageUrl, index) in getCommentImages(comment.commentImages)"
                  :key="index"
                  :src="getImageUrl(imageUrl)"
                  class="comment-image"
                  @click="previewCommentImage(imageUrl)"
                  @error="handleImageError"
                  alt="评论图片"
                />
              </div>
            </div>
          </div>

          <div class="comment-footer">
            <div class="status-section">
              <el-tag
                :type="comment.commentStatus === '0' ? 'success' : 'info'"
                size="small"
                class="status-tag"
              >
                {{ comment.commentStatus === '0' ? '显示中' : '已隐藏' }}
              </el-tag>
              <el-button
                :type="comment.commentStatus === '0' ? 'warning' : 'success'"
                size="small"
                @click="handleToggleStatus(comment)"
                class="toggle-btn"
              >
                {{ comment.commentStatus === '0' ? '隐藏' : '显示' }}
              </el-button>
            </div>
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleDeleteComment(comment.commentId!)"
            >
              删除评论
            </el-button>
          </div>
        </div>
      </transition-group>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ChatLineSquare, Delete, User } from '@element-plus/icons-vue';
import { getCommentsByUserId, deleteComment, toggleCommentStatus } from '@/api/comment';
import { getDishById } from '@/api/dish';
import { useUserStore } from '@/stores/user';
import type { Comment } from '@/types';
import { ElMessage, ElMessageBox } from 'element-plus';

const userStore = useUserStore();

const comments = ref<Comment[]>([]);
const loading = ref(false);

// 加载评论列表
const loadComments = async () => {
  if (!userStore.userId) return;
  
  loading.value = true;
  try {
    const response = await getCommentsByUserId(userStore.userId);
    if (response.operateResult === 'SUCC' && response.data) {
      // 加载每个评论的菜品信息
      const commentsWithDishes = await Promise.all(
        response.data.map(async (comment) => {
          const dishRes = await getDishById(comment.dishId);
          if (dishRes.operateResult === 'SUCC' && dishRes.data) {
            return { ...comment, dish: dishRes.data };
          }
          return comment;
        })
      );
      comments.value = commentsWithDishes.sort((a, b) => {
        return new Date(b.createTime || '').getTime() - new Date(a.createTime || '').getTime();
      });
    } else {
      comments.value = [];
    }
  } catch (error) {
    ElMessage.error('加载评论失败');
    comments.value = [];
  } finally {
    loading.value = false;
  }
};

// 切换评论状态
const handleToggleStatus = (comment: Comment) => {
  const newStatus = comment.commentStatus === '0' ? '1' : '0';
  const action = newStatus === '0' ? '显示' : '隐藏';
  
  ElMessageBox.confirm(`确定要${action}该评论吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await toggleCommentStatus(comment.commentId!, newStatus);
      if (response.operateResult === 'SUCC') {
        ElMessage.success(`${action}成功`);
        await loadComments();
      } else {
        ElMessage.error(response.errorMsg || `${action}失败`);
      }
    } catch (error: any) {
      ElMessage.error(error.message || `${action}失败`);
    }
  }).catch(() => {});
};

// 删除评论
const handleDeleteComment = (commentId: number) => {
  ElMessageBox.confirm('确定要删除该评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteComment(commentId);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('删除成功');
        await loadComments();
      } else {
        ElMessage.error(response.errorMsg || '删除失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '删除失败');
    }
  }).catch(() => {});
};

// 获取评论图片数组
const getCommentImages = (commentImages: string) => {
  if (!commentImages || !commentImages.trim()) {
    return [];
  }
  return commentImages.split(',').map(url => url.trim()).filter(url => url);
};

// 获取图片URL
const getImageUrl = (imagePath: string) => {
  if (!imagePath || !imagePath.trim()) {
    return 'https://via.placeholder.com/200x150?text=No+Image';
  }
  if (imagePath.startsWith('http')) {
    return imagePath;
  }
  return `http://localhost:8060${imagePath}`;
};

// 预览评论图片
const previewCommentImage = (imagePath: string) => {
  if (!imagePath || !imagePath.trim()) {
    ElMessage.warning('图片路径无效');
    return;
  }
  
  try {
    const imageUrl = getImageUrl(imagePath);
    
    // 创建图片预览窗口
    const previewWindow = window.open('', '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes');
    if (previewWindow) {
      previewWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
          <title>图片预览</title>
          <style>
            body {
              margin: 0;
              padding: 20px;
              background: #000;
              display: flex;
              justify-content: center;
              align-items: center;
              min-height: 100vh;
            }
            img {
              max-width: 100%;
              max-height: 100%;
              object-fit: contain;
              border-radius: 8px;
              box-shadow: 0 4px 20px rgba(255, 255, 255, 0.1);
            }
            .close-btn {
              position: fixed;
              top: 20px;
              right: 20px;
              background: rgba(255, 255, 255, 0.2);
              color: white;
              border: none;
              padding: 10px 20px;
              border-radius: 5px;
              cursor: pointer;
              font-size: 16px;
            }
            .close-btn:hover {
              background: rgba(255, 255, 255, 0.3);
            }
          </style>
        </head>
        <body>
          <button class="close-btn" onclick="window.close()">关闭</button>
          <img src="${imageUrl}" alt="评论图片" onerror="this.src='https://via.placeholder.com/500x400?text=图片加载失败'">
        </body>
        </html>
      `);
      previewWindow.document.close();
    } else {
      ElMessage.error('无法打开图片预览窗口，请检查浏览器设置');
    }
  } catch (error) {
    console.error('预览图片失败:', error);
    ElMessage.error('预览图片失败');
  }
};

// 图片加载错误处理
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = 'https://via.placeholder.com/200x150?text=No+Image';
};

// 格式化时间 - 显示完整日期时间
const formatTime = (time?: string) => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

onMounted(() => {
  loadComments();
});
</script>

<style scoped>
.comments-container {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.header-card {
  margin-bottom: 20px;
}

.header-card h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s ease;
}

.comment-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.comment-fade-enter-active,
.comment-fade-leave-active {
  transition: all 0.3s ease;
}

.comment-fade-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.comment-fade-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.dish-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.dish-details h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #303133;
}

.comment-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.comment-time {
  color: #909399;
  font-size: 12px;
}

.comment-content {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 15px;
}

.comment-content p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
}

.comment-images {
  margin-top: 12px;
}

.comment-image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.comment-image {
  width: 120px;
  height: 90px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  object-fit: cover;
  display: block;
}

.comment-image:hover {
  opacity: 0.8;
  transform: scale(1.02);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.comment-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-tag {
  margin-right: 5px;
}

.toggle-btn {
  font-size: 12px;
  padding: 4px 8px;
  height: 24px;
}
</style>
